import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../config/app_colors.dart';

/// 购物主题加载组件
/// 支持静态方法调用，简化使用接口
class JoyLoadingWidget {
  static bool _isShowing = false;
  static BuildContext? _context;
  static OverlayEntry? _overlayEntry;
  
  /// 显示加载框
  /// [context] 上下文
  /// [text] 自定义加载文字
  static void show(BuildContext context, {String? text}) {
    if (_isShowing) return;
    
    _isShowing = true;
    _context = context;
    
    _overlayEntry = OverlayEntry(
      builder: (context) => Material(
        color: AppColors.overlay.withOpacity(0.3),
        child: Center(
          child: Container(
            width: 100.w,
            height: 100.w,
            padding: EdgeInsets.all(16.w),
            decoration: BoxDecoration(
              color: AppColors.background,
              borderRadius: BorderRadius.circular(12.r),
              boxShadow: [
                BoxShadow(
                  color: AppColors.shadow,
                  offset: const Offset(0, 4),
                  blurRadius: 12,
                ),
              ],
            ),
            child: _LoadingContent(text: text ?? 'Loading...'),
          ),
        ),
      ),
    );
    
    Overlay.of(context).insert(_overlayEntry!);
  }
  
  /// 隐藏加载框
  static void hide() {
    if (!_isShowing) return;
    
    _overlayEntry?.remove();
    _overlayEntry = null;
    _isShowing = false;
    _context = null;
  }
  
  /// 检查是否正在显示
  static bool get isShowing => _isShowing;
  
  /// 强制关闭（用于异常情况）
  static void forceClose() {
    try {
      _overlayEntry?.remove();
    } catch (e) {
      // 忽略错误
    }
    _overlayEntry = null;
    _isShowing = false;
    _context = null;
  }
}

/// 内部加载内容组件
class _LoadingContent extends StatefulWidget {
  final String text;
  
  const _LoadingContent({required this.text});

  @override
  State<_LoadingContent> createState() => _LoadingContentState();
}

class _LoadingContentState extends State<_LoadingContent>
    with TickerProviderStateMixin {
  late AnimationController _cartController;
  late AnimationController _bounceController;
  late AnimationController _fadeController;
  
  late Animation<double> _cartRotation;
  late Animation<double> _bounceAnimation;
  late Animation<double> _fadeAnimation;

  @override
  void initState() {
    super.initState();
    
    // 购物车旋转动画控制器
    _cartController = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );
    
    // 商品跳动动画控制器
    _bounceController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );
    
    // 文字淡入淡出动画控制器
    _fadeController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    );
    
    // 购物车旋转动画
    _cartRotation = Tween<double>(
      begin: 0,
      end: 1,
    ).animate(CurvedAnimation(
      parent: _cartController,
      curve: Curves.linear,
    ));
    
    // 商品跳动动画
    _bounceAnimation = Tween<double>(
      begin: 0,
      end: 1,
    ).animate(CurvedAnimation(
      parent: _bounceController,
      curve: Curves.elasticOut,
    ));
    
    // 文字淡入淡出动画
    _fadeAnimation = Tween<double>(
      begin: 0.3,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _fadeController,
      curve: Curves.easeInOut,
    ));
    
    // 启动动画
    _startAnimations();
  }
  
  void _startAnimations() {
    // 购物车持续旋转
    _cartController.repeat();
    
    // 商品跳动动画循环
    _bounceController.repeat(reverse: true);
    
    // 文字淡入淡出循环
    _fadeController.repeat(reverse: true);
  }

  @override
  void dispose() {
    _cartController.dispose();
    _bounceController.dispose();
    _fadeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    const loadingColor = AppColors.primaryVariant;
    final loadingTextColor = AppColors.textSecondary;
    
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 动画区域
        SizedBox(
          width: 60.w,
          height: 30.w,
          child: Stack(
            alignment: Alignment.center,
            children: [
              // 购物车图标 - 旋转动画
              AnimatedBuilder(
                animation: _cartRotation,
                builder: (context, child) {
                  return Transform.rotate(
                    angle: _cartRotation.value * 2 * 3.14159,
                    child: Icon(
                      Icons.shopping_cart,
                      size: 18.sp,
                      color: loadingColor,
                    ),
                  );
                },
              ),
              
              // 商品图标们 - 跳动动画
              Positioned(
                left: 0,
                child: AnimatedBuilder(
                  animation: _bounceAnimation,
                  builder: (context, child) {
                    return Transform.translate(
                      offset: Offset(0, -_bounceAnimation.value * 6),
                      child: Icon(
                        Icons.shopping_bag,
                        size: 10.sp,
                        color: loadingColor.withOpacity(0.7),
                      ),
                    );
                  },
                ),
              ),
              
              Positioned(
                right: 0,
                child: AnimatedBuilder(
                  animation: _bounceAnimation,
                  builder: (context, child) {
                    return Transform.translate(
                      offset: Offset(0, -_bounceAnimation.value * 5),
                      child: Transform.scale(
                        scale: 0.8 + _bounceAnimation.value * 0.2,
                        child: Icon(
                          Icons.local_mall,
                          size: 8.sp,
                          color: loadingColor.withOpacity(0.6),
                        ),
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
        
        SizedBox(height: 8.h),
        
        // 加载文字 - 淡入淡出动画
        AnimatedBuilder(
          animation: _fadeAnimation,
          builder: (context, child) {
            return Opacity(
              opacity: _fadeAnimation.value,
              child: Text(
                widget.text,
                style: TextStyle(
                  fontSize: 12.sp,
                  color: loadingTextColor,
                  fontWeight: FontWeight.w500,
                ),
                textAlign: TextAlign.center,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            );
          },
        ),
        
        SizedBox(height: 6.h),
        
        // 进度指示器
        SizedBox(
          width: 60.w,
          child: LinearProgressIndicator(
            backgroundColor: loadingColor.withOpacity(0.2),
            valueColor: const AlwaysStoppedAnimation<Color>(loadingColor),
            minHeight: 2.h,
          ),
        ),
      ],
    );
  }
}